package com.stylefeng.thanks.modular.api.controller;

import com.stylefeng.thanks.core.base.controller.BaseController;
import com.stylefeng.thanks.core.base.tips.ErrorTip;
import com.stylefeng.thanks.core.util.JwtTokenUtil;
import com.stylefeng.thanks.modular.api.model.User;
import com.stylefeng.thanks.modular.api.dao.UserMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

/**
 * 免jwt接口集
 *
 * @author yfzhu
 * @Date 2018/7/20 23:39
 */
@Api("/api")
@RestController
@RequestMapping("/api")
public class ApiController extends BaseController {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * api登录接口，通过账号密码获取jwt
     */
    @ApiOperation(value = "/auth")
    @RequestMapping(value = "/auth",method = RequestMethod.POST)
    @Cacheable(value = "auth",key = "#username")
    public Object auth(@RequestParam("username") String username,
                       @RequestParam("password") String password) {

        /**
         * 测试集成的redis
         */
        redisTemplate.opsForValue().append("17639977887", "00000");
        redisTemplate.opsForValue().set("15172488142", "666666", 10L, TimeUnit.MINUTES);
        //获取数据库中的账号密码，准备比对
        /*User user = userMapper.getByAccount(username);*/
        User user = new User();
        user.setUserName(username);
        user = userMapper.selectOne(user);
        if (true) {
            HashMap<String, Object> result = new HashMap<>();
            result.put("jwt", JwtTokenUtil.generateToken(String.valueOf(user.getId())));

            /**
             * 以下是redis的集成
             */
            logger.info("ops1+++++++++++" +redisTemplate.opsForValue().get("17639977887"));
            logger.info("ops1+++++++++++" +redisTemplate.opsForValue().get("15172488142"));

            redisTemplate.delete("17639977887");
            redisTemplate.delete("15172488142");

            return result;
        } else {
            return new ErrorTip(500, "账号密码错误！");
        }

    }

    /**
     * 测试接口是否走鉴权
     */
    @RequestMapping(value = "/test", method = RequestMethod.POST)
    public Object test() {
        return SUCCESS_TIP;
    }

}

